package com.shqcjd.siemensglass.ui;

import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.RequiresApi;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.iv.recyclerview.TvRecyclerView;
import com.open.androidtvwidget.bridge.RecyclerViewBridge;
import com.open.androidtvwidget.leanback.recycle.RecyclerViewTV;
import com.open.androidtvwidget.view.MainUpView;
import com.orhanobut.logger.Logger;
import com.pgyersdk.crash.PgyCrashManager;
import com.pgyersdk.update.PgyUpdateManager;
import com.shqcjd.siemensglass.MyApp;
import com.shqcjd.siemensglass.R;
import com.shqcjd.siemensglass.adapter.SelectListAdapter;
import com.shqcjd.siemensglass.base.BaseActivity;
import com.shqcjd.siemensglass.bean.RemoteGuideBean;
import com.shqcjd.siemensglass.bean.UserStatusBean;
import com.shqcjd.siemensglass.http.ApiManager;
import com.shqcjd.siemensglass.http.BaseResult;
import com.shqcjd.siemensglass.http.Response;
import com.shqcjd.siemensglass.http.RxHttp;
import com.shqcjd.siemensglass.ui.remote.VideoChatViewActivity;
import com.shqcjd.siemensglass.utils.GlobalParams;
import com.shqcjd.siemensglass.utils.PrefUtils;
import com.shqcjd.siemensglass.utils.SpaceItemDecoration;
import com.shqcjd.siemensglass.utils.UIUtils;
import com.udevel.widgetlab.TypingIndicatorView;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import io.agora.AgoraAPI;
import io.agora.AgoraAPIOnlySignal;
import io.agora.IAgoraAPI;
import okhttp3.MediaType;
import okhttp3.RequestBody;

import static com.shqcjd.siemensglass.utils.Utils.getAndroidId;


public class SelectListActivity extends BaseActivity {

    @BindView(R.id.rv_user_list)
    RecyclerView rvUserList;
    @BindView(R.id.ib_up_arrow)
    ImageButton ibUpArrow;
    @BindView(R.id.tv_user_list)
    TvRecyclerView tvUserList;
    @BindView(R.id.ib_down_arrow)
    ImageButton ibDownArrow;
    @BindView(R.id.progress_view)
    TypingIndicatorView progressView;
    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.btn_cancel)
    Button btnCancel;
    @BindView(R.id.rl_wait_layout)
    RelativeLayout rlWaitLayout;

    private AgoraAPIOnlySignal mAgoraAPI;
    List<UserStatusBean> userList = new ArrayList<>();
    private SelectListAdapter selectListAdapter;
    private boolean isCall = false;//是否呼叫
    private String guidName;
    private String remoteAccount;
    private String channelName;
    private View lastFocusView;
    private boolean flag = true;

    public static final int REFRESH_TYPE_TIME = 4000;//4秒查询一次状态

    private Handler handler = new Handler();
    private Runnable r = new Runnable() {
        @Override
        public void run() {
            getData();
            handler.postDelayed(r, REFRESH_TYPE_TIME);
        }
    };
    private Context mContext;

    @Override
    public int getLayoutId() {
        return R.layout.activity_select_list;
    }


    @Override
    protected void onVoiceResult(String result) {
        Logger.i("识别结果:"+result);
        selectItem(result);

    }

    private void selectItem(String result) {
        int index = getIndex(result);
        if (index != -1) {
            int status = MyApp.the().getmAgoraAPI().getStatus();
            if (status == 2) {//2: 用户已登录。
                UserStatusBean mBean = userList.get(index);
                isCall = true;
                guidName = mBean.name;
                remoteAccount = mBean.id + "";
                tvName.setText(guidName);
                //查询用户是否在线 todo
                mAgoraAPI.queryUserStatus(remoteAccount);
                //展示呼叫等待
                rlWaitLayout.setVisibility(View.VISIBLE);
                btnCancel.requestFocus();
                progressView.stopDotAnimation();
                progressView.startDotAnimation();
            } else {
                MyApp.the().getmAgoraAPI().login2(UIUtils.getSaveAgoraAppId(mContext), getAndroidId(SelectListActivity.this), "_no_need_token", 0, "", 5, 1);
            }
        } else {
            switch (result) {
                case "返回":
                    finish();
                    break;
                case "取消":
                    isCall = false;
                    /*隐藏呼叫等待界面*/
                    rlWaitLayout.setVisibility(View.GONE);
                    progressView.stopDotAnimation();
                    /*取消呼叫 终止成功后主叫方将收到 onInviteEndByMyself() 回调。 */
                    callOutHangup();
                    if(lastFocusView!=null){
                        lastFocusView.requestFocus();
                    }
                    break;
            }
        }

    }

    private int getIndex(String result) {
        for (int i = 0; i < userList.size(); i++) {
            if (userList.get(i).name.equals(result)) {
                return i;
            }
        }
        return -1;
    }

    @Override
    protected boolean isAutomaticInitVoice() {
        return false;
    }

    @Override
    public void initView(Bundle savedInstanceState) {
        mContext = this;

        initAgoraEngineAndJoinChannel();

        /*焦点列表*/
        GridLayoutManager manager = new GridLayoutManager(this, 1);
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        manager.supportsPredictiveItemAnimations();

        selectListAdapter = new SelectListAdapter(userList);
        selectListAdapter.setHasStableIds(true);
        tvUserList.setLayoutManager(manager);
        tvUserList.addItemDecoration(new SpaceItemDecoration(0,8));
//        DefaultItemAnimator animator = new DefaultItemAnimator();
//        tvUserList.setItemAnimator(animator);
        tvUserList.setItemAnimator(null);
        tvUserList.setAdapter(selectListAdapter);
        tvUserList.setOnScrollListener(new OnPopRecyclerViewScrollListener());
        selectListAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                View rootview = SelectListActivity.this.getWindow().getDecorView();
                lastFocusView = rootview.findFocus();
                int status = MyApp.the().getmAgoraAPI().getStatus();
                if (status == 2) {//2: 用户已登录。
                    UserStatusBean mBean = userList.get(position);
                    isCall = true;
                    guidName = mBean.name;
                    remoteAccount = mBean.id+"";
                    tvName.setText(guidName);
                    //查询用户是否在线 todo
                    mAgoraAPI.queryUserStatus(remoteAccount);
                    //展示呼叫等待
                    rlWaitLayout.setVisibility(View.VISIBLE);
                    btnCancel.requestFocus();
                    progressView.stopDotAnimation();
                    progressView.startDotAnimation();
                } else {
                    MyApp.the().getmAgoraAPI().login2(UIUtils.getSaveAgoraAppId(mContext), getAndroidId(SelectListActivity.this), "_no_need_token", 0, "", 5, 1);
                }
            }
        });

        initPgy();

    }



    private void initPgy() {
        //蒲公英
        PgyCrashManager.register(); //推荐使用新版
        /** 蒲公英可选配置集成方式 **/
        new PgyUpdateManager.Builder()
                .setForced(false)                //设置是否强制提示更新
                // v3.0.4+ 以上同时可以在官网设置强制更新最高低版本；网站设置和代码设置一种情况成立则提示强制更新
                .setUserCanRetry(false)         //失败后是否提示重新下载
                .setDeleteHistroyApk(true)     // 检查更新前是否删除本地历史 Apk， 默认为true
                .register();
    }

    private void initAgoraEngineAndJoinChannel() {
        mAgoraAPI = MyApp.the().getmAgoraAPI();
    }

    @Override
    public void loadData() {
        handler.postDelayed(r, REFRESH_TYPE_TIME);
        getData();
    }

//    private void getUserList() {
//        new RxHttp<BaseResult<List<ExpertUserEnity>>>().send(ApiManager.getService().getExpertList(), new Response<BaseResult<List<ExpertUserEnity>>>(this, true) {
//            @Override
//            public void onNext(BaseResult<List<ExpertUserEnity>> result) {
//                super.onNext(result);
//                if (result.code == 0 && result.data != null) {
//                    userList.clear();
//                    userList.addAll(result.data);
//                    selectListAdapter.notifyDataSetChanged();
//                }
//
//            }
//        });
//    }

    private void getData() {
        new RxHttp<BaseResult<List<UserStatusBean>>>().send(ApiManager.getService().getUserStatus(), new Response<BaseResult<List<UserStatusBean>>>(this) {
            @Override
            public void onNext(BaseResult<List<UserStatusBean>> result) {
                super.onNext(result);
                if (result.code == 0 && result.data != null) {
                    userList.clear();
                    userList.addAll(result.data);
                    if (flag) {
                        flag = false;
                        getVoiceContent(addVoiceContent());
                        Logger.i("识别结果内容:"+addVoiceContent());
                    }
                    selectListAdapter.notifyDataSetChanged();
                }
            }
        });
    }

    private String addVoiceContent() {
        String str = "";
        for (UserStatusBean bean : userList) {
            str = str + "|"+bean.name;
        }

        return str + "|返回|取消;";
    }

    @OnClick({R.id.btn_cancel})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_cancel://取消呼叫
                isCall = false;
                /*隐藏呼叫等待界面*/
                rlWaitLayout.setVisibility(View.GONE);
                progressView.stopDotAnimation();
                /*取消呼叫 终止成功后主叫方将收到 onInviteEndByMyself() 回调。 */
                callOutHangup();
                if(lastFocusView!=null){
                    lastFocusView.requestFocus();
                }
                break;
        }

    }

    @Override
    protected void onResume() {
        super.onResume();
        addCallback();
        if(lastFocusView!=null){
            lastFocusView.requestFocus();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        View rootview = SelectListActivity.this.getWindow().getDecorView();
        lastFocusView = rootview.findFocus();
    }



    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(handler!=null){
            handler.removeCallbacks(r);
        }
    }

    //结束呼叫
    private void callOutHangup() {
        if (mAgoraAPI != null)
            mAgoraAPI.channelInviteEnd(channelName, remoteAccount, 0);
    }


    //添加信令监听
    private void addCallback() {
        if (mAgoraAPI == null) {
            return;
        }

        mAgoraAPI.callbackSet(new AgoraAPI.CallBack() {

            @Override
            public void onLogout(final int i) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (i == IAgoraAPI.ECODE_LOGOUT_E_KICKED) { // other login the account
                            Logger.i("其他登录帐户，你注销了");

                        } else if (i == IAgoraAPI.ECODE_LOGOUT_E_NET) { // net
                            Logger.i("注销网络不能");

                        }
                        finish();
                    }
                });

            }

            @Override
            public void onLoginFailed(int i) {
                Logger.i("onLoginFailed  i = " + i);
            }



            //当呼叫被对方收到时触发。，本地将回调 onInviteReceivedByPeer, 对方会回调 onInviteReceived。
            @Override
            public void onInviteReceivedByPeer(final String channelID, final String account, int uid) {//call out other local receiver


            }

            //当呼叫被对方接受时触发此回调。
            @Override
            public void onInviteAcceptedByPeer(String channelID, final String account, int uid, String extra) {
                super.onInviteAcceptedByPeer(channelID, account, uid, extra);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Logger.e("===对方确认");
                        rlWaitLayout.setVisibility(View.GONE);
                        progressView.stopDotAnimation();
                        Intent intent = new Intent(SelectListActivity.this, VideoChatViewActivity.class);
                        intent.putExtra("account", account);
                        intent.putExtra("channelName", channelName);
                        intent.putExtra("guidName", guidName);
                        startActivity(intent);
                    }
                });
            }

            @Override
            public void onInviteFailed(String channelID, String account, int uid, int i1, String s2) {
                Logger.i("onInviteFailed  channelID = " + channelID + " account = " + account + " s2: " + s2 + " i1: " + i1);
            }

            @Override
            public void onError(final String s, int i, final String s1) {
                Logger.i("onError s = " + s + " i = " + i + " s1 = " + s1);

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (s.equals("query_user_status")) {
                            Logger.i(s1);
                        }
                    }
                });
            }

            //用户状态查询回调 (onQueryUserStatusResult) 1: 用户在线 0: 用户离线
            @Override
            public void onQueryUserStatusResult(final String name, final String status) {
                Logger.i("onQueryUserStatusResult name = " + name + " status = " + status);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (status.equals("1")) {
                            //获取房间id 并发起呼叫
                            callInvitation();

                        } else if (status.equals("0")) {
//                            Toasty.info(SelectListActivity.this, "对方处于离线状态", Toast.LENGTH_SHORT, true).show();

                            new Handler().postDelayed(new Runnable(){
                                public void run() {
                                    //execute the task
                                    if (isCall) {
                                        mAgoraAPI.queryUserStatus(remoteAccount);
                                    }
                                }
                            }, 2000);
                        }
                    }
                });
            }

            //结束呼叫 本端会回调 onInviteEndByMyself，对端会回调 onInviteEndByPeer
            @Override
            public void onInviteEndByMyself(String channelID, String account, int uid) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                    }
                });
            }

            /**
             * 加入信令频道成功
             * @param channelID
             */
            @Override
            public void onChannelJoined(String channelID) {
                super.onChannelJoined(channelID);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        String username = PrefUtils.getString(mContext, PrefUtils.USER_NAME, "");
                        int userId = GlobalParams.getUserId();
                        Map<String, String> map = new HashMap<>();
                        map.put("name", username);//呼叫方姓名
                        map.put("userId", userId+"");//呼叫方id
                        map.put("channelID", channelName);//对应频道
                        map.put("mainID", userId+"");//对应的现场人员id（被指导者）
                        //发起呼叫                    成功：自己收到 ICallBack 类的 onInviteAcceptedByPeer() 回调
                        //channelID	频道名。  account 客户端定义的用户账号 uid	固定填 0
                        mAgoraAPI.channelInviteUser2(channelName, remoteAccount, new JSONObject(map).toString());
                    }
                });
            }
        });
    }


    /**
     * 获取房间号-----发起呼叫
     */
    private void callInvitation() {
        String agoraAppId = UIUtils.getSaveAgoraAppId(mContext);
        Map<String, String> map = new HashMap<>();
        map.put("guider",remoteAccount);
        map.put("agoraAppid",agoraAppId);
        String body = new Gson().toJson(map);
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), body);
        new RxHttp<BaseResult<RemoteGuideBean>>().send(ApiManager.getService().getRoomId(requestBody),new Response<BaseResult<RemoteGuideBean>>(this){
            @Override
            public void onNext(BaseResult<RemoteGuideBean> result) {
                super.onNext(result);
                if (result.code == 0) {
                    channelName = result.data.roomId;
                    Logger.i("房间id:"+channelName);
                    GlobalParams.savaRoomId(channelName);

                    //加入信令频道
                    MyApp.the().getmAgoraAPI().channelLeave(channelName);//离开
                    MyApp.the().getmAgoraAPI().channelJoin(channelName);//加入

                }
            }
        });

    }


    private class OnPopRecyclerViewScrollListener extends RecyclerView.OnScrollListener {
        @Override
        public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
            super.onScrollStateChanged(recyclerView, newState);
        }

        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            super.onScrolled(recyclerView, dx, dy);
            //在滚动的时候处理箭头的状态
            setUpArrStatus();
            setDownArrStatus();
        }
    }

    /**
     * 设置上箭头的状态
     */
    private void setUpArrStatus() {
        if (tvUserList.isFirstItemVisible()) {
            ibUpArrow.setVisibility(View.INVISIBLE);
        } else {
            ibUpArrow.setVisibility(View.VISIBLE);
        }

    }

    /**
     * 设置右侧箭头的状态
     */
    private void setDownArrStatus() {
        if (tvUserList.isLastItemVisible(1, userList.size())) {
            ibDownArrow.setVisibility(View.INVISIBLE);
        } else {
            ibDownArrow.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (event.getAction() == KeyEvent.ACTION_DOWN) {
            if (event.getKeyCode() == KeyEvent.KEYCODE_DPAD_LEFT) {
                KeyEvent keyEvent = new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DPAD_UP);
                simulateKey(keyEvent);

                return true;
            } else if (event.getKeyCode() == KeyEvent.KEYCODE_DPAD_RIGHT) {
                KeyEvent keyEvent = new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DPAD_DOWN);
                simulateKey(keyEvent);
                return true;
            }
        }
        return super.dispatchKeyEvent(event);
    }

    private void simulateKey(final KeyEvent keyCode) {
        new Thread() {
            @RequiresApi(api = Build.VERSION_CODES.N)
            @Override
            public void run() {
                try {
                    InputMethodManager systemService = (InputMethodManager) mContext.getSystemService(Context.INPUT_METHOD_SERVICE);
                    systemService.dispatchKeyEventFromInputMethod(getWindow().getDecorView().getRootView(), keyCode);
                } catch (Exception e) {

                }
            }

        }.start();

    }

}
